package org.knight.gearbox.concurrent.lock.distributed.db;

import org.knight.gearbox.concurrent.lock.Lock;
import org.knight.gearbox.concurrent.lock.LockProvider;

import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

public class DefaltLockProvider implements LockProvider {


    private final int cacheSize = 4096;
    private Map<String, Lock> lockCache = Collections.synchronizedMap(
            new LinkedHashMap<String, Lock>() {
                @Override
                public boolean removeEldestEntry(Map.Entry<String, Lock> eldest) {
                    return size() >= cacheSize;
                }
            }
    );

    @Override
    public Lock getLock(String name) {

        Lock lock = lockCache.get(name);

        if (lock != null) {
            return lock;
        }
        synchronized (this) {
            lock = lockCache.get(name);
            if (lock == null) {
                lock = new DefaultLock();
                lockCache.put(name, lock);
            }
        }
        return lock;
    }
}
